package domain;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.util.ArrayList;

import javax.sound.sampled.AudioInputStream;

public class ServerThread implements Runnable{
	
	public String serverIp;
	public static final int SERVERPORT = 8080;
	public static ArrayList<Socket> clients = new ArrayList<Socket>();
	
	private ServerSocket serverSocket;
	private String line;
	
	private Server server;
	
	public ServerThread(Server s){
		this.server = s;
		this.serverIp = s.getServerIp();
	}
	
	

	@Override
	public void run() {
		try{
			if(serverIp != null){
				System.out.println("Listening on ip: " + serverIp);
				
				serverSocket = new ServerSocket(SERVERPORT);
				while (true){
					Socket client = serverSocket.accept();
					clients.add(client);
					System.out.println(client.getInetAddress().getHostName() + "connected.");
					
					ClientSocketObject cso = new ClientSocketObject(client);
					Thread tCso = new Thread(cso);
					tCso.start();
					
				}
			} else {
				System.out.println("Couldn't detect a connection");
			}
		}catch (Exception e){
			System.out.println("there was an error: " + e.getMessage());
			try {
				serverSocket.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
		
		
	}

}
